<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox, ElButton, ElLoading, ElCard, ElDescriptions, ElTable, ElTableColumn, ElImage } from 'element-plus';

// 定义订单状态
const orderStatus = ref({
  '0': '全部订单',
  '1': '待付款',
  '2': '待发货',
  '3': '已取消',
});

// 要显示的订单列表
const orders = ref([]);

// 从 LocalStorage 获取已催促的订单ID
const getRemindedOrders = () => {
  const remindedOrders = localStorage.getItem('remindedOrders');
  return remindedOrders ? JSON.parse(remindedOrders) : [];
};

const remindedOrders = ref(getRemindedOrders()); // 初始化已催促的订单ID
const remindDisabled = ref(false);

// 获取订单按钮
const getOrderButtons = (orderStatus) => {
  switch (orderStatus) {
    case 1: // 待付款
      return [
        { label: '去支付', type: 'primary', action: payOrder },
        { label: '取消订单', type: 'danger', action: cancelPurchase }
      ];
    case 2: // 待发货
      return [
        { label: '催发货', type: 'primary', action: remindDelivery, disabled: remindDisabled.value },
      ];
    case 3: // 已取消
      return [];
    default:
      return [];
  }
};

// 加载订单
const loadOrdersByStatus = (status) => {
  axios.get(`/orders/loadOrdersByStatus?status=${status}`).then(resp => {
    orders.value = resp.data;
    console.log("加载订单", resp.data);
  });
};

// 生成唯一编码
const generateUniqueCode = () => {
  const timestamp = Date.now();
  const randomNum = Math.floor(Math.random() * 100000);
  return "WNXY_" + timestamp + randomNum.toString().padStart(5, '0');
};

// 支付订单
const payOrder = (row) => {
  console.log("执行支付操作", row);
  const uniqueCode = generateUniqueCode();
  const orderIdStr = row.toString();
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: '正在跳转到支付页面...',
    spinner: 'el-icon-loading'
  });

  axios.post('/orders/pay', {
    orderId: orderIdStr,
    uniqueCode: uniqueCode
  }).then(resp => {
    const divForm = document.getElementsByTagName("div");
    if (divForm.length) {
      document.body.removeChild(divForm[0]);
    }
    const div = document.createElement("div");
    div.innerHTML = resp.data;
    document.body.appendChild(div);
    document.forms[0].submit()
  }).catch(error => {
    ElMessage.error(`订单: WNXY_CAR_${orderIdStr}，支付失败：${error.response.data}`);
  });
};

// 取消订单
const cancelPurchase = (orderId) => {
  ElMessageBox.confirm(`您确定要取消该商品订单吗？`, '警告', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消',
    type: 'warning',
  }).then(() => {
    const token = localStorage.getItem('token');
    return axios.post(`/orders/cancel/${orderId}`, {}, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
  }).then((response) => {
    ElMessage.success(response.data);
    const order = orders.value.find(order => order.orderId === orderId);
    if (order) {
      order.orderStatus = 3;
    }
  }).catch((errorMsg) => {
    ElMessage({ type: 'info', message: errorMsg });
  });
};

// 催促发货
const remindDelivery = (orderId) => {
  if (remindedOrders.value.includes(orderId)) {
    ElMessage.info('您已催促过发货，请勿重复操作');
    return;
  }

  ElMessageBox.confirm('是否需要为您向商家催促发货', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'info'
  }).then(() => {
    axios.post('/orders/updateShipmentStatus', null, {
      params: {
        orderId: orderId,
        shipmentStatus: 1
      }
    }).then(() => {
      remindDisabled.value = true;
      ElMessage.success('已为您催促发货！请耐心等待');
      // 将已催促的订单ID存储到 localStorage
      remindedOrders.value.push(orderId);
      localStorage.setItem('remindedOrders', JSON.stringify(remindedOrders.value));
    }).catch(error => {
      ElMessage.error(`修改发货状态失败：${error.response.data}`);
      remindDisabled.value = false;
    });
  }).catch(() => {
    remindDisabled.value = false;
  });
};

// 激活的标签页名字
const activeName = ref(null);

// 加载全部订单
onMounted(() => {
  loadOrdersByStatus('0');
});

// 切换标签页
const handleClick = (tab) => {
  console.log(tab.name);
  loadOrdersByStatus(tab.props.name);
};

</script>


<template>
  <div>
    <el-card>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane :label="value" :name="key" v-for="(value, key, index) in orderStatus" :key="index">
          <div v-if="orders.length > 0">
            <div v-for="(order, index) in orders" :key="order.orderId" class="order-card">
              <el-card class="order-card-body">
                <el-descriptions title="订单详情" column="2" label-width="120px">
                  <el-descriptions-item label="订单编号：">{{ order.orderId }}</el-descriptions-item>
                  <el-descriptions-item label="订单总金额（元）：">{{ order.totalPrice }}</el-descriptions-item>
                  <el-descriptions-item label="下单时间：">{{ order.orderDate }}</el-descriptions-item>
                  <el-descriptions-item label="收货人：">{{ order.receiver }}</el-descriptions-item>
                  <el-descriptions-item label="收货地址：">{{ order.address }}</el-descriptions-item>
                  <el-descriptions-item label="联系电话：">{{ order.telephone }}</el-descriptions-item>
                </el-descriptions>

                <el-table :data="order.orderItem" style="width: 100%" border stripe>
                  <el-table-column prop="name" label="商品名称"></el-table-column>
                  <el-table-column prop="price" label="商品单价"></el-table-column>
                  <el-table-column prop="imgSrc" label="商品图片">
                    <template #default="{ row }">
                      <el-image
                          style="height: 120px;"
                          :src="$urlImage + row.imgSrc"
                          fit="contain"
                      ></el-image>
                    </template>
                  </el-table-column>
                  <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
                  <el-table-column prop="sumPrice" label="小计" width="100"></el-table-column>
                </el-table>

                <div class="order-footer">
                  <el-button
                      v-for="button in getOrderButtons(order.orderStatus)"
                      :key="button.label"
                      size="small"
                      round
                      :type="button.type"
                      @click="() => button.action(order.orderId)"
                      :disabled="remindedOrders.includes(order.orderId)"
                  >
                    {{ remindedOrders.includes(order.orderId) ? '您已催促过发货，请勿重复操作' : button.label }}
                  </el-button>
                </div>
              </el-card>
            </div>
          </div>
          <el-empty v-else description="没有查询到订单"></el-empty>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<style scoped>
.order-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
  padding: 15px;
}

.order-card-body {
  padding: 20px;
  background-color: #ffffff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.order-footer {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-table {
  margin-bottom: 20px;
}

.el-table-column {
  text-align: center;
}

.el-image {
  margin: 0 auto;
  display: block;
}

.el-button {
  padding: 6px 16px;
}

@media (max-width: 768px) {
  .order-container {
    padding: 10px;
  }

  .order-card {
    padding:10px;
  }
}
</style>